<template>
  <view class="markdownTextView">
    <view id="vditor"></view>
    <view v-if="loading" class="loadingClass">
      <u-loading size="24" color="#2979ff" />
      <text>加载中...</text>
    </view>
  </view>
</template>
<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";

const props = defineProps({
  value: {
    type: String,
    default: "",
  },
});

let dom = null;

const clickDom = (e) => {
  if (e.target.nodeName === "IMG") {
    uni.previewImage({
      urls: [e.target.src],
    });
  } else if (e.target.nodeName === "A") {
    window.open(e.target.href, "_blank");
    e.preventDefault();
  }
};

onMounted(() => {
  dom = document.querySelector("#vditor");
  dom.addEventListener("click", clickDom);
});

onUnmounted(() => {
  dom.removeEventListener("click", clickDom);
});

const loading = ref(false);

watch(
  () => props.value,
  (newValue) => {
    if (!newValue) return;
    loading.value = true;
    Vditor.preview(dom, newValue, {
      mode: "light",
      markdown: {
        toc: true,
        autoSpace: false,
        fixTermTypo: true,
      },
      hljs: {
        style: "github-dark",
        lineNumber: true,
      },
      math: {
        engine: "KaTeX",
        inlineDigit: true,
      },
      speech: {
        enable: false,
      },
      after: () => {
        loading.value = false;
      },
    });
  },
  {
    immediate: true,
  }
);
</script>
<style scoped lang="scss">
.markdownTextView {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  .loadingClass {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    align-items: center;
    justify-content: center;
    & > text {
      font-size: 14px;
      color: $u-tips-color;
      margin-left: 5px;
    }
  }
}

#vditor {
  max-width: 800px;
  user-select: text;
  :deep(p) {
    margin-bottom: 0.5em;
  }
}
</style>
